package hernanbosqued.parking;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

//adapter 1

public class AdapterParkings extends BaseAdapter
{
	private final int 			WARNING_CAPACITY_LIMIT = 20;
	private Context             context;
	private List<EntityParking> data;
	
	private class ViewHolder
	{		
		TextView	textview_nombre;
		TextView	textview_precio_hora;
		TextView	textview_distancia;
	}

	public AdapterParkings( Context p_context, Object p_data ) throws Exception
	{	
		context = p_context;		
		data    = new ArrayList<>( );
		
		Object[][] list = (Object[ ][ ]) p_data;	
		
		for( Object[] item : list )
		{
			data.add( EntityParking.getInstance( item ) );
		}
	}
	
	public void sortByDistance( Location p_location )
	{		
		for( EntityParking item : data )
		{
			item.setDistance( p_location );
		}
		
		if( p_location != null )
		{
			Collections.sort( data );
		}
		
		notifyDataSetChanged( );

	}
	
	@Override
	public int getCount( )
	{
		return data.size( );
	}

	@Override
	public long getItemId( int arg0 )
	{
		return 0;
	}

	@Override
	public View getView( int p_location, View p_view, ViewGroup p_parent )
	{
		ViewHolder holder;

		if ( p_view == null )
		{
			p_view = LayoutInflater.from( context ).inflate( R.layout.listview_item, p_parent, false );
			holder = new ViewHolder( );
			holder.textview_nombre       = (TextView ) p_view.findViewById( R.id.textview_nombre );
			holder.textview_precio_hora  = (TextView ) p_view.findViewById( R.id.textview_precio_hora );
			holder.textview_distancia    = (TextView ) p_view.findViewById( R.id.textview_distancia );
			p_view.setTag( holder );
		}
		else
		{
			holder = (ViewHolder) p_view.getTag( );
		}
	
		EntityParking parking = data.get( p_location );
		
		holder.textview_nombre.setText( parking.nombre );
		holder.textview_precio_hora.setText( parking.precio_hora );
		holder.textview_distancia.setText( parking.distancia < 0 ? context.getString( R.string.no_data ) : String.valueOf( Math.round( parking.distancia ) ) + context.getString( R.string.symbol_meters ) );
		p_view.setBackgroundColor( getBackgroundColor( parking ) );
		return p_view;
	}

	private int getBackgroundColor( EntityParking p_param )
	{
		if( p_param.cocheras_disponibles == 0 )
		{
			return Color.RED;
		}
		else if ( p_param.cocheras_disponibles > WARNING_CAPACITY_LIMIT )
		{
			return Color.GREEN;
		}
		else
		{
			return Color.YELLOW;
		}		
	}
	
	@Override
	public Object getItem( int position )
	{
		return null;
	}
}
